package com.zhiyun.service.impl;

import com.zhiyun.domain.Examination;
import com.zhiyun.domain.ExaminationRecord;
import com.zhiyun.domain.Response;
import com.zhiyun.mapper.ExaminationMapper;
import com.zhiyun.mapper.ExaminationRecordMapper;
import com.zhiyun.mapper.ResponseMapper;
import com.zhiyun.service.ExaminationService;
import com.zhiyun.util.Db;
import com.zhiyun.vo.ExaminationRecordVo;
import com.zhiyun.vo.ExaminationResponseVo;
import com.zhiyun.vo.Result;

import java.util.Date;
import java.util.List;

/**
 * @author zc
 * @Date 2025/5/6 下午7:07
 */
public class ExaminationServiceImpl implements ExaminationService {
    ExaminationMapper examinationMapper = Db.getMapper(ExaminationMapper.class);
    ExaminationRecordMapper examinationRecordMapper = Db.getMapper(ExaminationRecordMapper.class);
    ResponseMapper responseMapper = Db.getMapper(ResponseMapper.class);
    @Override
    public Result getExaminations(Integer courseId) {
        List<Examination> list = examinationMapper.selectByCourseId(courseId);
        return Result.ok(list);
    }

    @Override
    public Result getNotStartExaminations(Integer courseId) {
        List<Examination> list = examinationMapper.selectByCourseIdNotStart(courseId);
        return Result.ok(list);
    }

    @Override
    public Result getNowExaminations(Integer courseId) {
        List<Examination> list = examinationMapper.selectByCourseIdNow(courseId);
        return Result.ok(list);
    }

    @Override
    public Result getEndExaminations(Integer courseId) {
        List<Examination> list = examinationMapper.selectByCourseIdEnd(courseId);
        return Result.ok(list);
    }

    @Override
    public Result startExamination(Integer examinationId) {
        Examination examination = examinationMapper.selectById(examinationId);
        return Result.ok(examination);
    }


    @Override
    public Result submit(ExaminationRecordVo examinationRecordVo,Integer studentId) {
        try {
            Db.startTransaction();
            //得到考试记录vo中的examination
            Examination examination = examinationRecordVo.getExamination();
            //查看是否有该记录
            ExaminationRecord oldExaminationRecord = examinationRecordMapper.selectByEidAndSidWithResponse(examination.getId(), studentId);
            if (oldExaminationRecord != null) {
                return Result.fail("你已经提交过此次考试了,请勿重复提交");
            }
            //得到考试记录vo中的作答vo的集合
            List<ExaminationResponseVo> responseVos = examinationRecordVo.getResponseVos();
            //判断是不是在考试范围内
            if (!(examination.getStarttime().before(new Date()) && examination.getEndtime().after(new Date()))) {
                return Result.fail("不在考试时间范围内");
            }
            ExaminationRecord examinationRecord = new ExaminationRecord();//主键要回显
            examinationRecord.setExaminationId(examination.getId());
            examinationRecord.setStudentId(studentId);
            //得到总分
            examinationRecord.setScore(examinationRecordVo.getTotalScore());
            examinationRecord.setState(0);
            int rows = examinationRecordMapper.insert(examinationRecord);
            int row = 0;
            for (ExaminationResponseVo responseVo : responseVos) {
                Response response = new Response();
                //我的作答内容
                response.setContent(responseVo.getAnswerContent());
                //考试记录主键
                response.setExaminationRecordId(examinationRecord.getId());
                //题目id
                response.setQuestionId(responseVo.getTestQuestion().getId());
                //得分
                response.setScore(responseVo.getScore());
                row += responseMapper.insert(response);
            }
            if (!(rows == 1 && row == responseVos.size())){
                throw new Exception();
            }
            Db.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            Db.rollbackTransaction();
            return Result.fail("提交失败");
        } finally {
            Db.close();
        }
        return Result.okMsg("提交成功");
    }

    @Override
    public Result getExaminationDetails(Integer examinationId, Integer studentId) {
        ExaminationRecord examinationRecord = examinationRecordMapper.selectByEidAndSidWithResponse(examinationId,studentId);
        return Result.ok(examinationRecord);
    }

    @Override
    public Result addExamination(Examination examination) {
        int rows = examinationMapper.insert(examination);
        if (rows > 0){
            return Result.okMsg("发布考试成功");
        }
        return Result.fail("发布考试失败");
    }

    @Override
    public Result updateExamination(Examination examination) {
        Examination oldExamination = examinationMapper.selectByPrimaryKey(examination.getId());
        if (oldExamination == null) {
            return Result.fail("考试不存在");
        }
        int rows = examinationMapper.updateByPrimaryKey(examination);
        if (rows > 0){
            return Result.okMsg("修改成功");
        }
        return Result.fail("修改失败");
    }

    @Override
    public Result getAllStudentDetails(Integer examinationId) {
        Examination examination = examinationMapper.selectByPrimaryKey(examinationId);
        Integer courseId = examination.getCourseId();
        //拿到对应的考试id和课程id,先通过课程id查到所有学生,然后去查所有学生的这次考试的记录,外连接,学生必须全都有
        List<ExaminationRecord> examinationRecords = examinationRecordMapper.selectByExaminationIdWithStudent(examinationId,courseId);
        return Result.ok(examinationRecords);
    }

    @Override
    public Result getExaminationDetailsByRecordId(Integer recordId) {
        List<Response> responses = responseMapper.selectByExaminationReCordIdWithTestQuetion(recordId);
        return Result.ok(responses);
    }

    @Override
    public Result updateResponseScore(Integer responseId, Integer responseScore) {
        try {
            Db.startTransaction();
            Response response = responseMapper.selectByIdWithTestQuestion(responseId);
            if (response == null){
                return Result.fail("该作答记录不存在");
            }
            //修改的分值不能大于这道题的分值
            Integer score = response.getTestQuestion().getScore();
            if (responseScore < 0 && responseScore > score){
                return Result.fail("不能大于该题目最大分值");
            }
            response.setScore(responseScore);
            //修改response表
            int rows = responseMapper.updateByPrimaryKey(response);
            //修改examination_record表
            //得到这张卷子的所有题目
            List<Response> responses = responseMapper.selectByExaminationReCordIdWithTestQuetion(response.getExaminationRecordId());
            //重新计算这张卷子的分数
            int totalScore = 0;
            for (Response response1 : responses) {
                totalScore += response1.getScore();
            }
            ExaminationRecord examinationRecord = examinationRecordMapper.selectByPrimaryKey(response.getExaminationRecordId());
            examinationRecord.setScore(totalScore);
            int row = examinationRecordMapper.updateByPrimaryKey(examinationRecord);
            if (!(row == 1 && rows == 1)){
                return Result.fail("批改失败");
            }
            Db.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            Db.rollbackTransaction();
            return Result.fail("批改失败");
        } finally {
            Db.close();
        }
        return Result.okMsg("批改成功");
    }
}
